const fs = require('fs');

function readPackageJsonFile (path) {
  console.log(`Reading ${path} ...`);
  return new Promise(resolve => {
    fs.readFile(path, 'utf8', function (err, text) {
      if (err) {
        console.log(err);
        return;
      }
      resolve(text);
    });
  });
}

function writePackageJsonFile (path, json) {
  console.log(`Writing ${path} ...`);
  return new Promise(resolve => {
    fs.writeFile(path, JSON.stringify(json, null, 2), 'utf8', function (err) {
      if (err) {
        console.log(err);
        return;
      }
      console.log(`Written ${path} succeed...`);
      resolve();
    });
  });

}

function addVersion (text) {
  const textJson = JSON.parse(text);
  const version = textJson.version;
  const versionArr = version.split('.');
  versionArr[versionArr.length - 1] = Number.parseInt(versionArr[versionArr.length - 1]) + 1;
  textJson.version = versionArr.join('.');
  return textJson;
};

module.exports = {readPackageJsonFile, writePackageJsonFile, addVersion};


